/**
 * 设置驱动默认同步属性，默认根据字段相似名称映射，数据源同步属性只有一组，而目标源同步属性有多组
 * driver.sourceMapping.fileds : [{name=ID, type=4}, {name=NAME, type=12}]
 * driver.mappings.fileds : { [{name=ID, type=4}, {name=NAME, type=12}],[{name=ID, type=4}, {name=NAME, type=12}] }
 */
function setDefProperty(driver){
	var sourceMapping = driver.sourceMapping;
	var targetMapping = driver.targetMapping;
	
	var sourceArr = sourceMapping.config.column;
	var targetArr = targetMapping.config.column;
	var sLen = sourceArr.length;
	var tLen = targetArr.length;
	//驱动列
	var sourceCols = [];
	var targetCols = [];
	var sLen = sourceArr.length;
	var tLen = targetArr.length;
	for (var i = 0; i < sLen; i++) {
		var sCol = sourceArr[i];
		var sName = sCol.name;
		var tCol = null;
		for (var k = 0; k < tLen; k++) {
			var tFiled = targetArr[k];
			var tName = tFiled.name;
			if(sName==tName){
				tCol = tFiled;
				break;
			}
		}
		if(tCol != null){
			sourceCols.push(sCol);
			targetCols.push(tFiled);
		}
	}
	//赋值
	sourceMapping.fileds = sourceCols;
	targetMapping.fileds = targetCols;
}

/**
 * 设置默认数据源配置策略
 * @param driver
 * @returns
 */
function setDefPolicyForSource(driver){
	var policy = {
		"model": "log",
		"enable": "false"
	};
	var sourceMapping = driver.sourceMapping;
	switch (sourceMapping.connector) {
	case ConnectorConstantMysql:
		// 回现驱动数据源的信息
		policy.type = "mysql";
		break;
	case ConnectorConstantSqlMysql:
		policy.type = "sqlMysql";
		policy.table = "EXAMPLE";
		policy.tableLabel = "T1";
		break;
	case ConnectorConstantOracle:
		policy.type = "oracle";
		policy.dictionary = "/oracle/logmnr/dictionary.ora";
		break;
	case ConnectorConstantSqlOracle:
		policy.type = "sqlOracle";
		policy.dictionary = "/oracle/logmnr/dictionary.ora";
		break;
	case ConnectorConstantSqlServer:
		policy.type = "sqlserver";
		break;
	case ConnectorConstantLdap:
		policy.type = "ldap";
		var config = sourceMapping.config;
		policy.url = config.url;
		policy.base = config.base;
		policy.userDn = config.userDn;
		policy.password = config.password;
		policy.searchScope = config.searchScope;
		break;
	case ConnectorConstantWebService:
		policy.type = "ws";
		//默认Webservice仅支持同步模式
		driver.model = "increment";
		break;
	default:
		break;
	}
	driver.policy.increment = policy;
}

//设置驱动名称
function getDriverName(driver){
	var sourceConfigName = driver.sourceMapping.name.toLocaleUpperCase();
	var targetConfigName = driver.targetMapping.name.toLocaleUpperCase();
	var defVal = sourceConfigName+"_"+targetConfigName;
	var dirverNameHtml='<form class="form-horizontal" role="form">'
						+'<div class="form-group">'
						+'<div class="col-sm-12">'
						+'<p>请输入驱动名称(1-50个字符)</p>'
						+'<input type="text" class="form-control required" name="driverName" maxlength="50" placeholder="请输入驱动名称(1-50个字符)" value="'+defVal+'">'
						+'</div>'
						+'</div>'
						+'</form>';
	BootstrapDialog.show({
		title : "驱动名称",
		type : BootstrapDialog.TYPE_INFO,
		message : dirverNameHtml,
		size:BootstrapDialog.SIZE_NORMAL,
		buttons : [{
			label : "确定",
			action : function(dialog){
				// 获取表单输入值
				var info = dialog.getModalContent();
				var success = false;
				// 如果输入框值为空，则高亮显示
				$(info).find("input.required").each(function() {
					if ($(this).val() != "" && $(this).val().length <= 50) {
						$(this).removeClass("driverVerifcateError");
						success = true;
						return true;
					}
					$(this).addClass("driverVerifcateError");
				});
				// 触发 keyup 事件
				$(info).find("input.required").keyup(function() {
					$(this).removeClass("driverVerifcateError");
					if ($(this).val() == "" && $(this).val().length > 50) {
						$(this).addClass("driverVerifcateError");
					}
				});
				if(!success){
					return;
				}
				// 设置驱动名称
				driver.name = $(info).find('input[name="driverName"]').val();
				submit(driver);
				dialog.close();
			}
			},{
				label : "取消",
				action : function(dialog){			    
				dialog.close();
			}
		}]
	});

	// 兼容IE PlaceHolder
	$('input[type="text"],input[type="password"]').ASDPlaceHolder();
}

/**
 * 配置数据源和目标源信息
 * @param mapping
 * @param $config
 * @return
 */
function setDriverConfig(mapping, $config){
	var config = validataDriverConfig($config);
	if(config){
		mapping.name = config.name;
		mapping.connector = config.connector;
		mapping.config = config;
		mapping.fileds = [];
		// 去掉重复的属性
		delete config.name;
		delete config.connector;
		return true;
	}
	return false;
}

function check(){
	var driver = {
		"appId": $("#appId").text().trim(),
		"appName": $("#appName").text().trim(),
		"name": null,
		"model": "all",
		"enable": true,
		"sourceMapping": {},
		"targetMapping": {},
		"query": {
			"and":[],
			"or":[]
		},
		"policy": {}
	};
	//1.检查数据源/目标源配置
	var res = setDriverConfig(driver.sourceMapping, $("#sourceConfig"));
	if(!res){
		return;
	}
	res = setDriverConfig(driver.targetMapping, $("#targetConfig"));
	if(!res){
		return;
	}
	
	//4.设置默认策略
	setDefPolicyForSource(driver);
	//5.设置驱动默认同步属性，默认根据字段相似名称映射
	setDefProperty(driver);
	//6.设置驱动名称
	getDriverName(driver);
}

function submit(driver){
	//保存驱动配置
	$.loadingT(true);
	$.post($basePath + "/driver/add", {"mapping":JSON.stringify(driver)}, function(data) {
		$.loadingT(false);
        if(data.success==true){
        	bootGrowl("新增驱动成功!","success"); 
			$initContainer.load($basePath+'/driver/page/driverEdit?driverId='+data.resultValue);
		}else{
			bootGrowl(data.resultValue,"danger"); 
		}
	});
}

//切换连接器
function changeConnectorType($this){
	//连接器类型
	var connType = $this.val();
	//获取连接器配置元素
	var connectorConfig = $this.parent().parent().parent().find(".connectorConfig");
	//清空配置
	connectorConfig.html("");
	
	//从公共配置文件中读取配置的驱动页面地址
	for (var key in DriverConnectorConstant) {
		if(connType==key){
			var val = DriverConnectorConstant[key];
			//加载页面
			connectorConfig.load($basePath+val['url']);
			break;
		}
	}
}

$(function() {
	// 兼容IE PlaceHolder
	$('input[type="text"],input[type="password"],textarea').ASDPlaceHolder();
	
	// 初始化select2插件
	$(".select-control").select2({
		width : "100%",
		theme : "classic"
	});
	
	//连接器切换事件
	$("select[name='connector']").change(function(){
		changeConnectorType($(this));
	});
	
	//保存
	$("#driverSubBtn").click(function(){
		check();
	});
	
	//返回
	$("#driverBackIndexBtn").click(function(){
		//加载页面,在IE浏览器下,防止请求从缓存加载,故加上refresh时间戳参数
		$initContainer.load($basePath+"/index?refresh="+new Date().getTime());
	});
})